package site.wlwsjsx.iot_backend.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ExceptionHandler;
import site.wlwsjsx.iot_backend.service.exception.*;
import site.wlwsjsx.iot_backend.utils.JsonResultUtil;

public class BaseController {
    //操作成功
    public static final int OK = 200;

    @ExceptionHandler(ServiceException.class) //统一处理抛出的异常
    public JsonResultUtil<Void> handleException(Throwable e) {
        JsonResultUtil<Void> result = new JsonResultUtil<>();
        if (e instanceof UsernameNotFoundException) {
            result.setState(4000);
            result.setMessage("用户名不存在");
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(4001);
            result.setMessage("用户名或密码错误");
        } else if (e instanceof UsernameDuplicatedException) {
            result.setState(5000);
            result.setMessage("用户名已经被占用");
        } else if (e instanceof InvalidUsernameException) {
            result.setState(5001);
            result.setMessage("用户名不合法");
        } else if (e instanceof InvalidPasswordException) {
            result.setState(5002);
            result.setMessage("密码不合法");
        } else if (e instanceof IllegalArgumentException) {
            result.setState(6000);
            result.setMessage("设备类型错误，必须是 'lab' 或 'workstation'");
        } else {
            result.setState(404);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    protected final Integer getUidFromSession(HttpSession httpSession) {
        return Integer.valueOf(httpSession.getAttribute("uid").toString());
    }

    protected final Integer getUsernameFromSession(HttpSession httpSession) {
        return Integer.valueOf(httpSession.getAttribute("userName").toString());
    }
}
